package com.abel.mvc.service.impl;

import com.abel.mvc.entity.Mail;
import com.abel.mvc.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;

/**
 * @author abel.he
 * @data 2018/8/11 10:12
 */
@Service("messageService")
public class MessageServiceImpl implements MessageService {

    @Autowired
    JmsTemplate jmsTemplate;

    @Override
    public void sendMessage(String from, String to, String subject, String content) {
        if (to.indexOf(";") > 0) {
            String[] toArr = to.split(";");
            for (String toTmp :
                    toArr) {
                if (toTmp == null || "".equals(toTmp.trim())) {
                    continue;
                }

                final Mail mail = transObjectToMail(from, toTmp, subject, content);
                send(mail);
            }
        } else {
            final Mail mail = transObjectToMail(from, to, subject, content);
            send(mail);
        }


    }


    private void send(final Mail mail) {
        jmsTemplate.send(new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                ObjectMessage message = session.createObjectMessage(mail);
                return message;
            }
        });
    }

    private Mail transObjectToMail(String from, String toTmp, String subject, String content) {
        Mail mail = new Mail();
        mail.setFrom(from);
        mail.setTo(toTmp);
        mail.setSubject(subject);
        mail.setContent(content);
        return mail;
    }

}
